<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="800px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-form-item label="酒店名称" prop="title">
                    <el-input v-model="formData.title" clearable placeholder="请输入酒店名称" />
                </el-form-item>
                <el-form-item label="城市" prop="city">
                    <el-cascader
                        v-model="selectedCity"
                        :options="cities"
                        :props="{
                            value: 'value',
                            label: 'text',
                            children: 'children',
                            checkStrictly: true
                        }"
                        placeholder="请选择省市区"
                        clearable
                        @change="handleCityChange"
                    />
                </el-form-item>
                <!-- <el-form-item label="省份" prop="province">
                    <el-input v-model="formData.province" clearable placeholder="请输入省份" />
                </el-form-item>
                <el-form-item label="区" prop="district">
                    <el-input v-model="formData.district" clearable placeholder="请输入区" />
                </el-form-item> -->
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="formData.address" clearable placeholder="请输入详细地址" />
                    <!-- <el-button type="primary" @click="searchAddress" style="margin-top: 10px;">搜索地址</el-button> -->
                </el-form-item>
                <el-form-item label="封面图" prop="cover">
                    <el-input v-model="formData.cover" clearable placeholder="请输入封面图" :disabled="true"/>
                    <material-picker v-model="formData.cover" :limit="1" />
                </el-form-item>
                <el-form-item label="轮播图" prop="photos">
                    <!-- <el-input v-model="formData.photos" clearable placeholder="请输入轮播图" /> -->
                    <material-picker v-model="formData.photos" :limit="5"/>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" clearable placeholder="请输入联系电话" />
                </el-form-item>
                
                <el-form-item label="配置服务" prop="basic">
                    <el-select v-model="basicVale" clearable placeholder="请选择配置服务" @change="handleBasicChange" multiple >
                        <el-option
                            v-for="item in basicList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="最低价格" prop="price">
                    <el-input v-model="formData.price" clearable placeholder="请输入最低价格" />
                </el-form-item>
                <el-form-item label="最低原价" prop="origin_price">
                    <el-input v-model="formData.origin_price" clearable placeholder="请输入最低原价" />
                </el-form-item> -->
                <el-form-item label="简介" prop="desc">
                    <el-input v-model="formData.desc" clearable placeholder="请输入简介" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="酒店地址">
                    <div class="search-box">
                        <el-input v-model="searchKeyword" placeholder="搜索地址" style="width: 300px;">
                            <template #append>
                                <el-button @click="searchAddress">搜索</el-button>
                            </template>
                        </el-input>
                    </div>
                    <div class="map-container" ref="mapContainer">
                        <div id="map" style="width: 100%; height: 400px;" ref="mapBox"></div>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="经度" prop="longitude">
                    <el-input v-model="formData.longitude" clearable placeholder="请输入经度" :disabled="true"/>
                </el-form-item>
                <el-form-item label="维度" prop="latitude">
                    <el-input v-model="formData.latitude" clearable placeholder="请输入维度" :disabled="true"/>
                </el-form-item> -->
                <!-- <el-form-item label="1 正常 0 删除" prop="status">
                    <el-input v-model="formData.status" clearable placeholder="请输入1 正常 0 删除" />
                </el-form-item> -->
                <!-- <el-form-item label="" prop="ctime">
                    <el-input v-model="formData.ctime" clearable placeholder="请输入" />
                </el-form-item>
                <el-form-item label="" prop="utime">
                    <el-input v-model="formData.utime" clearable placeholder="请输入" />
                </el-form-item> -->

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="hotelEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiHotelAdd, apiHotelEdit, apiHotelDetail } from '@/api/hotel'
import { apiHotelBasicLists } from '@/api/hotel_basic'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { cities } from '@/utils/citys'
import feedback from '@/utils/feedback'
// 声明腾讯地图类型
// declare const TMap: any
// declare global {
//     interface Window {
//         TMap: any
//     }
// }
// 地图相关
const searchKeyword = ref('')
let map: any = null
let marker: any = null
let geocoder: any = null

const basicList = ref<any[]>([])
const basicVale = ref<any[]>([])

// 配置服务变化
const handleBasicChange = () => {
    formData.basic = basicVale.value
}
const getBasicList = async () => {
    const data = await apiHotelBasicLists({
        page_no: 1,
        page_size: 10000
    })
    basicList.value = data.lists.map((item: any) => ({
        label: item.title,
        value: item.id
    }))
}
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑酒店表' : '新增酒店表'
})

// 表单数据
const formData = reactive({
    id: '',
    title: '',
    city: '',
    province: '',
    district: '',
    address: '',
    cover: '',
    photos: [],
    phone: '',
    desc: '',
    price: '',
    origin_price: '',
    longitude: '',
    latitude: '',
    status: '',
    ctime: '',
    utime: '',
    basic: [] as any[],
})


// 表单验证
const formRules = reactive<any>({
    title: [{
        required: true,
        message: '请输入酒店名称',
        trigger: ['blur']
    }],
    city: [{
        required: true,
        message: '请输入城市',
        trigger: ['blur']
    }],
    province: [{
        required: true,
        message: '请输入省份',
        trigger: ['blur']
    }],
    district: [{
        required: true,
        message: '请输入区',
        trigger: ['blur']
    }],
    cover: [{
        required: true,
        message: '请输入封面图',
        trigger: ['blur']
    }],
    photos: [{
        required: true,
        message: '请输入轮播图',
        trigger: ['blur']
    }],
    phone: [{
        required: true,
        message: '请输入联系电话',
        trigger: ['blur']
    }],
    price: [{
        required: true,
        message: '请输入最低价格',
        trigger: ['blur']
    }],
})

// 城市选择相关
const selectedCity = ref<string[]>([])

// 处理城市选择变化
const handleCityChange = (value: string[]) => {
    if (value && value.length === 3) {
        const [provinceCode, cityCode, districtCode] = value
        const province = cities.find(p => p.value === provinceCode)
        const city = province?.children?.find(c => c.value === cityCode)
        const district = city?.children?.find(d => d.value === districtCode)

        formData.province = province?.value || ''
        formData.city = city?.value || ''
        formData.district = district?.value || ''
    } else {
        formData.province = ''
        formData.city = ''
        formData.district = ''
    }
}

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
        if(key == 'basic'){
            basicVale.value = data[key]
        }
    }
    
    // 根据已有的省市区信息设置级联选择器的值
    if (formData.province && formData.city && formData.district) {
        const province = cities.find(p => p.value == formData.province)
        if (province) {
            const city = province.children?.find(c => c.value == formData.city)
            if (city) {
                const district = city.children?.find(d => d.value == formData.district)
                if (district) {
                    selectedCity.value = [province.value, city.value, district.value]
                }
            }
        }
    }

    if(formData.latitude && formData.longitude){
        console.log('1111111')
        if(map){
            console.log('222222222')
            map.setCenter(new TMap.LatLng(Number(formData.latitude), Number(formData.longitude)))
            updateMarker(Number(formData.latitude), Number(formData.longitude))
            reverseGeocoder(Number(formData.latitude), Number(formData.longitude))
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiHotelDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()

    const data = { ...formData }
    mode.value == 'edit' 
        ? await apiHotelEdit(data) 
        : await apiHotelAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    console.log('open')
    mode.value = type
    popupRef.value?.open()
    console.log(toRaw(formData))
    getBasicList()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

// 地图相关变量


// 初始化地图
const initMap = () => {
    // 创建地图实例
    map = new TMap.Map('map', {
        center: new TMap.LatLng(39.909186, 116.397411),
        zoom: 12
    })
    // 创建标记
    marker = new TMap.MultiMarker({
        map: map,
        styles: {
            "marker": new TMap.MarkerStyle({
                width: 25,
                height: 35,
                anchor: { x: 12.5, y: 35 }
            })
        },
        geometries: []
    })
    // 创建地理编码服务
    geocoder = new TMap.service.Geocoder({
        complete: (result: any) => {
            console.log('地理编码服务初始化完成')
        }
    })
    // 点击地图事件
    map.on("click", (evt: any) => {
        const lat = evt.latLng.getLat()
        const lng = evt.latLng.getLng()
        updateMarker(lat, lng)
        reverseGeocoder(lat, lng)
    })
    if(formData.latitude && formData.longitude){
        updateMarker(Number(formData.latitude), Number(formData.longitude))
        map.setCenter(new TMap.LatLng(Number(formData.latitude), Number(formData.longitude)))
        reverseGeocoder(Number(formData.latitude), Number(formData.longitude))
    }
}

// 更新标记位置
const updateMarker = (lat: number, lng: number) => {
    marker.updateGeometries([{
        "id": "marker",
        "styleId": "marker",
        "position": new TMap.LatLng(lat, lng)
    }])
    formData.latitude = lat.toString()
    formData.longitude = lng.toString()
}

// 地理编码（地址转坐标）
const geocode = async (address: string) => {
    console.log(geocoder)
    console.log(address)
    try {
        const result = await geocoder.getLocation({
            address: address
        })
        if (result.status === 0 && result.result.location) {
            const { lat, lng } = result.result.location
            map.setCenter(new TMap.LatLng(lat, lng))
            updateMarker(lat, lng)
        }
    } catch (error: any) {
        console.error('地理编码失败:', error)
        if(error.status == 348){
            feedback.msgError('请输入完整酒店地址')
        }
    }
}

// 逆地理编码（坐标转地址）
const reverseGeocoder = async (lat: number, lng: number) => {
    console.log(lat, lng)
    try {
        const result = await geocoder.getAddress({
            location:  new TMap.LatLng(lat, lng)
        })
        if (result.status === 0 && result.result.address) {
            // formData.address = result.result.address
            searchKeyword.value = result.result.address
        }
    } catch (error) {
        console.error('逆地理编码失败:', error)
    }
}

// 搜索地址
const searchAddress = () => {
    if (searchKeyword.value) {
        geocode(searchKeyword.value)
    }
}
const mapContainer = ref<HTMLElement | null>(null);
const mapBox = ref<HTMLElement | null>(null);

onMounted(async () => {
    // 统一通过环境变量读取 Key
    const key = import.meta.env.VITE_TMAP_KEY
    if(!key){
        feedback.msgError('缺少腾讯地图 Key 配置(VITE_TMAP_KEY)')
        return
    }
})

watch(mapBox, async (newValue)=>{
    if(mapBox.value){
        // 动态加载 TMap GL SDK（避免重复注入）
        const key = import.meta.env.VITE_TMAP_KEY
        if(!key){
            feedback.msgError('缺少腾讯地图 Key 配置(VITE_TMAP_KEY)')
            return
        }
        // 若已存在则直接初始化
        if (window.TMap && window.TMap.service) {
            nextTick(() => {
                const mapElement = document.getElementById('map')
                if (mapElement) initMap()
            })
            return
        }
        const script = document.createElement('script')
        script.src = `https://map.qq.com/api/gljs?v=1.exp&key=${key}&libraries=service`
        script.onload = () => {
            if (window.TMap && window.TMap.service) {
                nextTick(() => {
                    const mapElement = document.getElementById('map')
                    if (mapElement) initMap()
                    else console.error('地图容器元素不存在')
                })
            } else {
                console.error('腾讯地图 API 加载失败')
                feedback.msgError('腾讯地图 API 加载失败')
            }
        }
        script.onerror = () => {
            console.error('腾讯地图 API 脚本加载失败')
            feedback.msgError('腾讯地图 API 脚本加载失败')
        }
        document.head.appendChild(script)
    }
})

onUnmounted(() => {
    try{
        // 简单清理引用以帮助 GC
        map && map.off && map.off('click')
    }catch(e){}
    map = null
    marker = null
    geocoder = null
})
defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style scoped>
.map-container {
    position: relative;
    width: 100%;
    height: 400px;
    margin-top: 10px;
}

.search-box {
    margin-bottom: 10px;
}
</style>
